<template>
  <div class="navigation-menu">
    <div
      class="menu__item"
      v-for="item in navigationMenu"
      :key="item.id"
      :style="{
        backgroundColor: selectedMenuId === item.id ? '#046743' : '#198b5c'
      }"
      @click="goPath(item)"
    >
      <img :src="setSrc(item.icon)" alt="" />
      {{ item.title }}
    </div>
    <div class="menu__item" @click="goBack">
      <img src="@/assets/menuIcon/back.svg" alt="" />
      返回上级
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  NavMenuItem,
  NAV_BAR_MENU_PATH,
  navMenuGoPath,
  getTopLevelMenu
} from '@/config/navigationMenu'

defineOptions({
  name: 'LayoutCpnNavigationMenu'
})

const router = useRouter()
const route = useRoute()

const navigationMenu = computed<NavMenuItem[]>(() => {
  if (route.path === NAV_BAR_MENU_PATH && route.query.id) {
    return getTopLevelMenu(Number(route.query.id))?.children || []
  }
  return getTopLevelMenu(route.path)?.children || []
})

let selectedMenuId = ref(0)
watch(
  () => route.path,
  () => {
    const selectedId = navigationMenu.value.find(
      (item) => item.path === route.path
    )?.id
    if (selectedId) {
      selectedMenuId.value = selectedId
    }
  },
  {
    immediate: true
  }
)

const goPath = (item: NavMenuItem) => {
  // 选中的菜单颜色加深
  selectedMenuId.value = item.id
  navMenuGoPath(router, item)
}

const goBack = () => {
  router.go(-1)
}

// 引入图标
const setSrc = (name?: string) => {
  return new URL(`../../../../assets/menuIcon/${name}.svg`, import.meta.url)
    .href
}
</script>

<style lang="scss" scoped>
.navigation-menu {
  display: flex;
  width: 100%;
  height: 100%;
  .menu__item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-right: 2px solid #ffffff;
    cursor: pointer;
    font-size: 18px;
    img {
      width: 55px;
      height: 55px;
      margin-bottom: 10px;
    }
    &:last-child {
      border-right: none;
      background-color: #f1aa37;
    }
  }
}
</style>
